package com.eye.system.service.impl;

import com.eye.common.utils.SecurityUtils;
import com.eye.system.domain.Task;
import com.eye.system.exception.DMPException;
import com.eye.system.mapper.TaskMapper;
import com.eye.system.search.TaskSearch;
import com.eye.system.service.TaskService;
import com.eye.system.util.CommonUtil;
import com.eye.system.util.PageRequest;
import com.eye.system.util.PageResult;
import com.eye.system.util.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("taskService")
public class TaskServiceImpl implements TaskService {

    @Resource
    private TaskMapper taskMapper;

    @Override
    public Integer addTask(Task task) {
        if (task != null) {
            task.setCreateDate(CommonUtil.getSystemTime(CommonUtil.FORMAT_STR_SECOND));
            task.setCreateBy(SecurityUtils.getUsername());
            int add = taskMapper.insert(task);
            if (add > 0) {
                return add;
            }
            throw new DMPException("添加任务失败");
        }
        throw new DMPException("无效参数");
    }

    @Override
    public Integer deleteTask(Integer id) {
        Integer delete = taskMapper.deleteById(id);
        if (delete > 0) {
            return delete;
        }
        throw new DMPException("删除任务失败");
    }

    @Override
    public Integer updateTask(Integer id, Task task) {
        Task t = taskMapper.selectById(id);
        if (t == null) {
            throw new DMPException("该任务不存在");
        }
        task.setUpdateDate(CommonUtil.getSystemTime(CommonUtil.FORMAT_STR_SECOND));
        task.setUpdateBy(SecurityUtils.getUsername());
        Integer update = taskMapper.updateByIdSelective(task);
        if (update > 0) {
            return update;
        }
        throw new DMPException("修改任务失败");
    }

    @Override
    public Task selectById(Integer id) {
        Task task = taskMapper.selectById(id);
        if (task != null) {
            return task;
        }
        throw new DMPException("该任务不存在");
    }

    @Override
    public PageResult selectPaging(TaskSearch taskSearch) {
        PageRequest pageRequest = new PageRequest();
        return PageUtils.getPageResult(pageRequest, getPageInfo(taskSearch));
    }

    private PageInfo<Task> getPageInfo(TaskSearch taskSearch) {
        PageHelper.startPage(taskSearch.getPageNum(), taskSearch.getPageSize());
        List<Task> taskList = taskMapper.select(taskSearch);
        return new PageInfo<Task>(taskList);
    }
}
